<template>
	<view class="tupu-content"
		:style="{ height: `calc(100vh - 88rpx - 88rpx - 300rpx - ${StatusBarRpx}rpx - var(--window-bottom))` }">
		<!-- 使用renderjs -->
		<view :prop="option" :change:prop="echarts.update" class="echarts" id="echarts"></view>
	</view>
</template>

<script>
	export default {
		props: {
			course: String
		},
		data() {
			return {
				rawData: [],
				option: {
					backgroundColor: '#fff',
					series: [{
						type: 'graph',
						layout: 'force',
						roam: true,
						force: {
							repulsion: 400,
							edgeLength: 10
						},
						data: []
					}]
				}
			};
		},
		mounted() {
			this.get_course_chapterApi();
		},
		methods: {
			async get_course_chapterApi() {
				let res = await this.$api.post(global.apiUrls.post680edf12c8757, {
					course_id: this.course,
				});


				console.log('00000000000000000000000', res);
				if (res.data.code == 1) {
					this.rawData = res.data.data.list.map((item) => {
						return {
							name: item.name,
							value: item.aid,
							size: this.getRandomFromArray()
						}
					});

					this.$emit('myEvent', res.data.data.num);

					// 准备option数据
					const fontSize = 11;
					this.option.series[0].data = this.rawData.map(item => ({
						name: this.wrapText(item.name, item.size, fontSize),
						value: item.value,
						symbolSize: item.size,
						symbol: 'image://static/img02/yuan.png',
						draggable: true,
						label: {
							show: true,
							position: 'inside',
							fontSize,
							color: '#FFFFFF',
							align: 'center',
							verticalAlign: 'middle',
							lineHeight: fontSize + 2,
						}
					}));
				}
			},

			//节点大小
			getRandomFromArray() {
				const arr = [120, 130, 110, 100, 90, 80];
				const index = Math.floor(Math.random() * arr.length);
				return arr[index];
			},

			// 自适应换行文本
			wrapText(text, symbolSize, fontSize = 14) {
				const avgCharWidth = fontSize * 0.6;
				const maxLineWidth = symbolSize * 0.5; // 留出 padding
				const maxCharsPerLine = Math.max(2, Math.floor(maxLineWidth / avgCharWidth));
				const lines = [];
				for (let i = 0; i < text.length; i += maxCharsPerLine) {
					lines.push(text.slice(i, i + maxCharsPerLine));
				}
				return lines.join('\n');
			}
		}
	};
</script>

<script module="echarts" lang="renderjs">
	import * as echarts from 'echarts';

	let chart = null;

	export default {
		mounted() {
			const tryInit = () => {
				const el = document.getElementById('echarts') || document.querySelector('.echarts');
				if (!el || el.nodeType !== 1 || !el.offsetWidth || !el.offsetHeight) {
					setTimeout(tryInit, 50);
					return;
				}
				this.init();
			};
			setTimeout(tryInit, 0);
		},
		unmounted() {
			if (chart) {
				chart.dispose();
				chart = null;
			}
		},
		methods: {
			init() {
				const el = document.getElementById('echarts') || document.querySelector('.echarts');
				if (!el || el.nodeType !== 1) {
					return;
				}
				chart = echarts.init(el);
				const isDark = document.body.getAttribute('data-theme') === 'dark';
				if (isDark) {
					chart.setOption({ backgroundColor: '#1e1e1e' });
				}
				if (this.prop) {
					this.update(this.prop);
				}
				chart.on('click', (params) => {
					uni.navigateTo({
						url: `/pages/course/chapterDetail/chapterDetail?aid=${params.value}&name=${params.name.replace(/\n/g, '')}`
					});
				});
			},
			update(newOption) {
				if (!chart) {
					const el = document.getElementById('echarts') || document.querySelector('.echarts');
					if (el && el.nodeType === 1 && el.offsetWidth && el.offsetHeight) {
						chart = echarts.init(el);
					} else {
						return;
					}
				}
				chart.setOption(newOption);
			},
			resize() {
				if (chart) {
					chart.resize();
				}
			}
		}
	};
</script>

<style scoped>
	.tupu-content {
		min-height: 80%;
		width: 100%;
	}

	.echarts {
		width: 100%;
		height: 100%;
	}
</style>